from django.db import transaction
from typing import Dict, Type
from ..demoapp.repository.demo_user_repository import DemoUserRepository


class UnitOfWork:
    """工作单元模式，管理所有仓储和事务"""
    def __init__(self):
        self._repositories: Dict[str, object] = {}
        self._init_repositories()
    
    def _init_repositories(self):
        """初始化所有仓储"""
        self._repositories['demo_users'] = DemoUserRepository()
    
    def __getattr__(self, name: str):
        """通过属性访问仓储"""
        if name in self._repositories:
            return self._repositories[name]
        raise AttributeError(f"仓储 {name} 不存在")
    
    @transaction.atomic
    def commit(self):
        """提交事务"""
        pass  # Django事务自动管理
    
    @transaction.atomic
    def rollback(self):
        """回滚事务"""
        transaction.set_rollback(True)
    
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is not None:
            self.rollback()
        else:
            self.commit()